package com.bieyang.anjia.ui.activity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.bieyang.anjia.utils.ApplicationUtils;
import com.bieyang.anjia.utils.NetUtils;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 * 公用一个service
 * */
public class PubService extends Service {
	static boolean canStartTask = true;
	public static boolean isrun = true;
	public static ExecutorService threadPool = Executors
			.newSingleThreadExecutor();
	Runnable runnable;
	public static long beat = 30 ;
	
	private Handler handler = new Handler();

	@Override
	public void onCreate() {
		super.onCreate();
		initTask();
	}

	void initTask() {
		if (null == runnable) {
			runnable = new Runnable() {
				@Override
				public void run() {
					System.out.println("task created");
					synchronized (threadPool) {
						canStartTask = false;
					}
					while (isrun) { 
						Log.d("isrun", String.valueOf(isrun)+":"+beat);
						try {
							Thread.sleep(beat*1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if (isrun &&  ApplicationUtils.netState(App.mContext)) {
							int ret=App.netManager.sendAlive();
							Log.d("ret", ""+ret);
							if(ret!=0 ){
								App.netManager.loginEx(handler);							
							}
						}
					}
					synchronized (threadPool) {
						canStartTask = true;
					}
				}
			};
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.d("PubService", "PubService");
		if (null == App.mContext) {
			App.mContext = getApplicationContext();
		}
		if (canStartTask) {
			threadPool.execute(runnable);
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		runnable = null;
		System.out.println("task destroy");
	}
}
